package reader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.text.DateFormatter;

import action.ActionPool;

/**
 * 
 * @author Minodor
 * 
 *         Splits each Line in the scenario into tokens (space-separated words);
 * 
 */
public class LineTokenizer {
	private static BufferedReader crReader = null;
	private final static File crWords = new File("Tokens/CompoundReservedWords");
	private final static Vector<String> predefinedTokens = new Vector<String>();
	private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	private Vector<String> splitted;
	private StringTokenizer st;
	private Vector<String> tokens;

	public LineTokenizer() {
		splitted = new Vector<String>();
		tokens = new Vector<String>();
		try {
			crReader = new BufferedReader(new FileReader(crWords));
			String nextLine;
			while ((nextLine = crReader.readLine()) != null)
				predefinedTokens.add(nextLine);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private String buildTokens(String s) {
		for (int i = 0; i < predefinedTokens.size(); i++) {

			int check = s.indexOf(predefinedTokens.get(i));
			if (check != (-1)) {
				s = s.replace(predefinedTokens.get(i), (predefinedTokens.get(i)
						.replace(' ', '_')));
			}
		}
		int t = s.lastIndexOf(" at ");
		if (t != (-1)) {
			s = s.substring(0, t + 1) + s.substring(t + 1).replace(' ', '_');
		} else {
			t = s.lastIndexOf(" from ");
			if (t != (-1)) {
				s = s.substring(0, t + 1)
						+ s.substring(t + 1).replace(' ', '_');
			}
		}
		System.out.println(" TOKENIZED STRING: " + s);
		return s;
	}

	public Vector<String> getNextLineTokens() {
		return this.tokens;
	}

	public boolean split(String s) {
		splitted = new Vector<String>();
		if(s.startsWith("#Day")){
			if(validate(s)){
			ActionPool.setCurrentDate(s.substring(5));
			}
			return false;
		}
		String tokens = buildTokens(s);
		st = new StringTokenizer(tokens);
		while (st.hasMoreElements()) {
			splitted.add(st.nextToken());
		}
		this.tokens = splitted;
		return true;

	}

	private boolean validate(String s) {
		String[] day=s.split(" ");
		if(day.length!=2)
			return false;
		try{
		format.parse(day[1]);
		}
		catch(Exception e)
		{
			return false;
		}
		return true;
		
	}
	
	public static void main(String args[])
	{
		LineTokenizer lt=new LineTokenizer();
		lt.validate("#Day 27/11/2011");
	}

}
